// from SDL/src/atomic/SDL_atomic.c
#include <stdbool.h>

//#define HAVE_GCC_ATOMICS 0

typedef struct {
    int value;
} Atomic_t;

// 原子操作
bool atomic_CAS(Atomic_t * a, int oldval, int newval);
int atomic_add(Atomic_t * a, int v);
int atomic_get(Atomic_t * a);
int atomic_set(Atomic_t * a, int v);

#ifndef atomic_incref
#define atomic_incref(a)    atomic_add(a, 1)
#endif

#ifndef atomic_decref
#define atomic_decref(a)    (atomic_add(a, -1) == 1)
#endif

// 自旋锁
typedef Atomic_t SpinLock;

bool spin_trylock(SpinLock * lock);
void spin_lock(SpinLock * lock);
void spin_unlock(SpinLock * lock);


// 互斥锁 (mem_* 用于内存管理)

#include <stdlib.h>

typedef void * (* malloc_func)(size_t size);
typedef void * (* calloc_func)(size_t nmemb, size_t size);
typedef void * (* realloc_func)(void *mem, size_t size);
typedef void   (* free_func)(void *mem);

void * mem_malloc(size_t size);
void * mem_calloc(size_t nmemb, size_t size);
void * mem_realloc(void * ptr, size_t size);
void * mem_free(void * ptr);

#include <stdio.h>
#include <pthread.h>

typedef struct {
    pthread_mutex_t id;
} Mutex;

Mutex * mutex_create(void);

void mutex_destroy(Mutex * mutex);
int mutex_lock(Mutex * mutex);
#define EBUSY       16  /* Device or resource busy */
#define MUTEX_TIMEDOUT 1

int mutex_trylock(Mutex * mutex);
int mutex_unlock(Mutex * mutex);
